package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sun.tools.doclint.Entity.and;

@Service
public class AdUserServiceImpl  extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    //用户登入
    @Override
    public ResponseResult login(UserDto dto) {

        System.out.println(dto.getName());
        System.out.println(dto.getPassword());
        //1.检查参数
        if(StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码错误");
        }
        dto.checkParam();

        List<AdUser> list = list(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(list!=null &&list.size()==1){
            AdUser adUser = list.get(0);
            String password = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
            //比对密码
          if(adUser.getPassword().equals(password)){
              //密码正确
              Map<String, Object>map =new HashMap();
              map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
              map.put("user",adUser);
              adUser.setPassword("");
              adUser.setSalt("");
              return ResponseResult.okResult(map);
          }else{
              //密码错误
              return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
          }
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
    }

    @Override
    public ResponseResult insert(AdUser user) {
        return null;
    }

    @Override
    public ResponseResult update(AdUser user) {
        return null;
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        return null;
    }
}
